package com.zhangkeyou.map.mapweb.mapper.handler;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.ibatis.type.*;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.*;
import java.util.function.BiConsumer;
import java.util.function.BinaryOperator;
import java.util.function.Function;
import java.util.function.Supplier;
import java.util.stream.Collector;
import java.util.stream.Collectors;

@MappedJdbcTypes(JdbcType.BLOB)
@MappedTypes(List.class)
public class FeatureFieldsTypeHandler extends BaseTypeHandler<List<Map<String, String>>> {

    @Override
    public void setNonNullParameter(PreparedStatement preparedStatement, int i, List<Map<String, String>> maps, JdbcType jdbcType) throws SQLException {
        String result = JSON.toJSONString(maps);
        preparedStatement.setNString(i,result);
    }

    @Override
    public List<Map<String, String>> getNullableResult(ResultSet resultSet, String s) throws SQLException {
        String result = resultSet.getString(s);
        List<Map> jsonObject = JSON.parseArray(result,Map.class);

        List<Map<String,String>> r = new ArrayList<>();

        jsonObject.forEach(map -> {
            r.add(new HashMap<>(map));
        });
        return r;
    }

    @Override
    public List<Map<String, String>> getNullableResult(ResultSet resultSet, int i) throws SQLException {
        JSONObject jsonObject = JSON.parseObject(resultSet.getString(i));
        return (List<Map<String, String>>) jsonObject;
    }

    @Override
    public List<Map<String, String>> getNullableResult(CallableStatement callableStatement, int i) throws SQLException {
        JSONObject jsonObject = JSON.parseObject(callableStatement.getString(i));
        return (List<Map<String, String>>) jsonObject;
    }
}
